#pragma once
#include <iostream>
#include "Common.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "Common.hpp"

#define FIFO_DEFAULT "named"

class NamedFifo
{
public:
    NamedFifo(std::string &&fifo = FIFO_DEFAULT)
        : _fifo(fifo)
    {
        umask(0);
        int n = mkfifo(_fifo.c_str(), 0666);
        if (n != 0)
        {
            ERR_EXIT("mkfifo");
        }
    }
    ~NamedFifo()
    {
        unlink(_fifo.c_str());
    }

private:
    std::string _fifo;
};

class FifoOper
{
public:
    FifoOper(int flag, std::string &&fifo = FIFO_DEFAULT)
        : _fifo(fifo)
    {
        _fd = open(_fifo.c_str(), flag);
        if(_fd == -1)
        {
            ERR_EXIT("open");
        }
    }
    void Write(std::string message)
    {
        write(_fd, message.c_str(), message.size());
    }
    int Read()
    {
        char buffer[1024];
        int n = read(_fd, buffer, sizeof(buffer) - 1);
        return n;
    }
    ~FifoOper()
    {
        close(_fd);
    }

private:
    std::string _fifo;
    int _fd;
};